package com.vchello.util;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.vchello.contants.CONTANTS;

/**
 * 
 * @author power
 *
 */
public final class UploadFileHelper{
	//上传文件
	/**
	 * @param type	是否临时文件
	 * @param file
	 * @param imagePath
	 * @return
	 * @throws IOException
	 */
	public static String uploadFile(int type, File file, String imagePath){
		if(file == null){
			return null;
		}
		String imageFile = ""; 
		String realpath = CONTANTS.FILE_ROOTPATH;
		String str = "";
		if(type == CONTANTS.FILE_TYPE[0]){
			str="/"+CONTANTS.UPLOAD_TEMPFILE+"/"+Utility.getDateNow()+"/"+Utility.getUUID()+"/";
		}else if(type == CONTANTS.FILE_TYPE[1]){
			str="/"+CONTANTS.UPLOAD_FILE+"/"+Utility.getDateNow()+"/"+Utility.getUUID()+"/";
		}
		try {
			imagePath = StringEscapeUtils.unescapeHtml4(imagePath);
			int index = imagePath.lastIndexOf("/");
			if(index != -1){
				imageFile=imagePath.substring(index+1,imagePath.length()).replaceAll(",", "").replaceAll("，", "");
			} else {
				imageFile=imagePath.replaceAll(",", "").replaceAll("，", "");
				for (int i = 0; i < CONTANTS.FILE_TYPES.length; i++) {
					if(imageFile.endsWith(CONTANTS.FILE_TYPES[i])){
						int index2 = imageFile.lastIndexOf(".");
			        	if(index2 == -1)
			        		break;
			        	String endPath = imageFile.substring(index2+1);
						imageFile = Utility.getUUID()+"."+endPath;
						break;
					}
				}
			}
	        if (file != null) {
	            File savefile = new File(new File(realpath),str+imageFile);
	            if (!savefile.getParentFile().exists()){
	            	savefile.getParentFile().mkdirs();
	            	try {
	            		FileUtils.copyFile(file, savefile);
	            		//上传原图
	            		String oldName = imagePath.substring(0,imagePath.length()-4);
	            		if(oldName.length() >4 && imagePath.endsWith(oldName.substring( oldName.length()-4, oldName.length()))){
	            			File oldFile =new File(realpath+oldName);
	            			if(oldFile.isFile() && oldFile.exists()){
	            				File oldSavefile = new File(new File(realpath),str+"_old_"+imageFile);
	            				FileUtils.copyFile(oldFile, oldSavefile);
	            			}
	            		}
	            	} catch (IOException e) {
	            		e.printStackTrace();
	            	}
	            }
	       }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str+imageFile;	
	}
	
	/**图片压缩
	 * 
	 */
	public static void compressPic(String filePath,String fileName,String text){
		if(StringUtils.isNotBlank(fileName)){
			String start = fileName.substring(0,fileName.lastIndexOf("/")+1);
			String end = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
			String returnPath = start+text+end;
			//CompressPicDemo.compressPic(filePath+fileName, filePath+"/"+returnPath,CONTANTS.PIC_PIXEL[1],CONTANTS.PIC_PIXEL[1],true);
		}
	}
	
    /**
     *  根据路径删除指定的目录或文件，无论存在与否
     *@param sPath  要删除的目录或文件
     *@return 删除成功返回 true，否则返回 false。
     */
    public static boolean DeleteFolder(String sPath,int type,HttpServletRequest request) {
       boolean flag = false;
       String realpath = request.getSession().getServletContext().getRealPath("");
       sPath = realpath + sPath;
        File file = new File(sPath);
        // 判断目录或文件是否存在
        if (!file.exists()) {  // 不存在返回 false
            return flag;
        } else {
            // 判断是否为文件
            if (file.isFile()) {  // 为文件时调用删除文件方法
                return deleteFile(sPath,type, request);
            } else {  // 为目录时调用删除目录方法
                return deleteDirectory(sPath,type);
            }
        }
    }
    /**
     * 删除目录（文件夹）以及目录下的文件
     * @param   sPath 被删除目录的文件路径
     * @return  目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath,int type) {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
    	boolean flag;
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFileName(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath(),type);
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 删除单个文件上层文件夹和文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath,int type,HttpServletRequest request) {
         String realpath =request.getSession().getServletContext().getRealPath("/");
         sPath = realpath +sPath;
         int index = sPath.lastIndexOf("/");
         if(index == -1)
        	 return false;
         String path = sPath.substring(0,index);
         if(CONTANTS.FILE_TYPE[0] == type){
        	 if(sPath.contains(CONTANTS.UPLOAD_TEMPFILE)){
        		 return deleteDirectory(path,type);
        	 }
         }
         if(CONTANTS.FILE_TYPE[1] == type){
        	 if(sPath.contains(CONTANTS.UPLOAD_FILE)){
        		 return deleteDirectory(path,type);
        	 }
         }
		return false;
    }
    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFileName(String sPath) {
       boolean flag = false;
//       String realpath = ServletActionContext.getServletContext().getRealPath("");
//       sPath = realpath +sPath;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
    
    /**
     * 上传文件到临时文件夹
     * @param file
     * @param fileName
     * @param request
     * @return
     * @throws IOException
     */
	public static String uploadTempFile(MultipartFile file, String fileName,HttpServletRequest request) throws IOException {
		try {
			String tempFile = CONTANTS.UPLOAD_TEMPFILE+"/"+Utility.getDateNow()+"/"+Utility.getUUID()+"/";
			for (int i = 0; i < CONTANTS.FILE_TYPES.length; i++) {
				if(fileName.endsWith(CONTANTS.FILE_TYPES[i])){
					int index2 = fileName.lastIndexOf(".");
		        	if(index2 == -1)
		        		break;
		        	String endPath = fileName.substring(index2+1);
		        	fileName = Utility.getUUID()+"."+endPath;
					break;
				}
			}
			ServletContext.class.getResource("/");
			String filePath = request.getSession().getServletContext().getRealPath("/")+File.separator+tempFile+fileName;
			
			File myFile = new File(filePath);
			if(!myFile.getParentFile().exists()){
				myFile.getParentFile().mkdirs();
			}
			file.transferTo(myFile);
			
			return "/"+tempFile+fileName;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 上传文件到正式文件夹
	 * @param file
	 * @param fileName
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String uploadFolderTempFile(MultipartFile file, String fileName,HttpServletRequest request) throws IOException {
		// TODO Auto-generated method stub
		try {
			String tempFile = CONTANTS.UPLOAD_FILE+File.separator+Utility.getDateNow()+File.separator+Utility.getUUID()+File.separator;
			for (int i = 0; i < CONTANTS.FILE_TYPES.length; i++) {
				if(fileName.endsWith(CONTANTS.FILE_TYPES[i])){
					int index2 = fileName.lastIndexOf(".");
					if(index2 == -1)
						break;
					String endPath = fileName.substring(index2+1);
					fileName = Utility.getUUID()+"."+endPath;
					break;
				}
			}
			String filePath = tempFile+fileName;
//			String filePath = request.getSession().getServletContext().getRealPath("/")+File.separator+tempFile+fileName;
			
			File myFile = new File(CONTANTS.FILE_ROOTPATH + File.separator + filePath);
			if(!myFile.getParentFile().exists()){
				myFile.getParentFile().mkdirs();
			}
			file.transferTo(myFile);
			
			return "/"+tempFile+fileName;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 文件管理上传
	 * @param file
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String uploadFolderFile(File file, String fileName) throws IOException {
		// TODO Auto-generated method stub
		return uploadFile(CONTANTS.FILE_TYPE[1], file, fileName);
	}
	
	/**
	 * 
	 * @param filePath
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String isFileExists(String filePath, HttpServletRequest request) throws IOException {
		String realpath = request.getSession().getServletContext().getRealPath("/");
		filePath = StringEscapeUtils.unescapeHtml4(filePath);
		File file = new File(realpath+filePath);
		if(filePath.contains(CONTANTS.UPLOAD_FILE)){
				return filePath;
		}else if(filePath.contains(CONTANTS.UPLOAD_TEMPFILE)){
			if(file.isFile() && file.exists()){
				String str = uploadFile(CONTANTS.FILE_TYPE[1], file, filePath);
				return str;
			}
		}
		return null;
	}
	
}